package cn.lj.dao.impl;

import cn.lj.dao.AccountDao;
import cn.lj.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author lj
 * @Description:
 * @date 2020-12-02 17:53
 * @QQ 851477108
 */

@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public Account findAccountById(Integer accountId) {
        String sql = "select * from account where id = ?";
        assert super.getJdbcTemplate() != null;
        List<Account> accounts = super.getJdbcTemplate().query(sql,new BeanPropertyRowMapper<>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        String sql = "select * from account where name = ?";
        assert super.getJdbcTemplate() != null;
        List<Account> accounts = super.getJdbcTemplate().query(sql,new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        String sql = "update account set name=?,money=? where id=?";
        assert super.getJdbcTemplate() != null;
        super.getJdbcTemplate().update(sql,account.getName(),account.getMoney(),account.getId());
    }
}
